package com.ywgt.thread;

public class Factory {
    public static void main(String[] args) {
        A a=new A();
        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    a.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"A").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    a.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"C").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    a.increment();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"B").start();

        new Thread(()->{
            for (int i=0;i<10;i++){
                try {
                    a.decrement();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"D").start();
    }
}

class A{

    private int i=0;

    public synchronized void increment() throws InterruptedException {
        while (i!=0){
           //等待
           this.wait();
        }
        i++;
        //完成，通知其他线程
        System.out.println(Thread.currentThread().getName()+i);
        this.notifyAll();
    }

    public synchronized void decrement() throws InterruptedException {
        while (i==0){
            //等待
            this.wait();
        }
        i--;
        //完成，通知其他线程
        System.out.println(Thread.currentThread().getName()+i);
        this.notifyAll();
    }
}
